package com.uu.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
@RequestMapping("/sse")
@Slf4j
@CrossOrigin
public class SseEmitterController {

    private SseEmitter sseEmitter;

    @GetMapping("/sub")
    public SseEmitter start() {
        if (sseEmitter == null) {
            sseEmitter = new SseEmitter(0L);
        }
        log.info("新连接");
        return sseEmitter;
    }

    @RequestMapping("/send")
    public String send() {
        try {
            sseEmitter.send(System.currentTimeMillis() + "");
        } catch (Exception e) {
            log.error("send 异常：{}", e.getLocalizedMessage(), e);
        }
        return "success";
    }
}
